package util;

import groove.GrooveClient;
import groove.json.util.SearchResult;
import groove.json.util.SongInfo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;

import com.example.myfirstapp.R;

public class SearchResultAdapter extends BaseAdapter{
	
	private SearchResult result;
	private LayoutInflater inflater;
	private GrooveClient client;
	private Activity context;
	
	public SearchResultAdapter(Activity context, SearchResult result, GrooveClient client){
		inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		this.result = result;
		this.client = client;
		this.context = context;
	}

	@Override
	public int getCount() {
		if(result == null)
			return 0;
		else
			return result.getSongs().size();
	}

	@Override
	public Object getItem(int position) {
		if(result == null)
			return null;
		else
			return result.getSongs().get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		
		final SongInfo song = result.getSongs().get(position);
		
		View rowView = inflater.inflate(R.layout.query_result_row, parent, false);
		
		TextView songTitle = (TextView) rowView.findViewById(R.id.textview_songtitle);
		TextView songAlbumArtist = (TextView) rowView.findViewById(R.id.textview_songartist_songalbum);
		
		songTitle.setText(song.getSongName());
		songAlbumArtist.setText(song.getArtistName() + " - " + song.getAlbumName());
		
		ImageButton downloadButton = (ImageButton) rowView.findViewById(R.id.button_add_download);
		downloadButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View paramView) {
				
				Helper.doToast("GEKLICKT!!!!", context);
				new GrooveClientDownloadTask(context, client, song).execute();
				
			}
		});
		
		return rowView;
	}
	
}
